import hashlib
import json
from datetime import datetime, timedelta

import jwt
from django.core.paginator import Paginator
from django.db.models.expressions import result
from django.forms.models import model_to_dict
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

# Create your views here.
from .models import User,Category,Book
from django.http import JsonResponse

def is_empty(c):
    return c is None or str(c).strip()==''

def jiami(c):
    return hashlib.md5(c.encode()).hexdigest()

@csrf_exempt
@require_http_methods(['POST'])
def dl(request):
    data=json.loads(request.body)
    username=data['username']
    password=data['password']

    if is_empty(username) or is_empty(password):
        return JsonResponse({"msg":"不能为空"})

    if User.objects.filter(username=username).exists()==False:
        return JsonResponse({"msg":"不存在"})

    a=User.objects.get(username=username)

    if jiami(password)!=a.password:
        return JsonResponse({"msg": "密码错误"})

    t=datetime.now() + timedelta(minutes=2)

    # t=datetime.now() + timedelta(minutes=30)
    pay={'id':a.id,'exp':int(t.timestamp())}


    mi='123456'

    token=jwt.encode(pay,mi)

    return JsonResponse({"msg": "登录成功","token":token},json_dumps_params={'ensure_ascii':False})


@csrf_exempt
def cha(request):
    # mi = '123456'
    # token = request.META.get('HTTP_TOKEN')
    # if not token:
    #     return JsonResponse({"msg": "请先登录"})
    # try:
    #     pay = jwt.decode(token, mi, algorithms=['HS256'])
    # except jwt.ExpiredSignatureError:
    #     return JsonResponse({"msg": "过期"})
    # except jwt.InvalidTokenError:
    #     return JsonResponse({"msg": "token无效"})

    # 查询的方法
    if request.method=="GET":
        data = Book.objects.all()
        chang = len(data)

        name = request.GET.get('name', '')
        status=request.GET.get('status', '')
        page = request.GET.get('page', 1)
        pagesize = request.GET.get('pagesize') or 10

        if name:
            data = data.filter(name__icontains=name)
        if status:
            data = data.filter(status=status)

        fy = Paginator(data, pagesize)
        data = fy.get_page(page)

        list = []
        for i in data:
            list.append(model_to_dict(i))


        return JsonResponse({"data": list, "total":chang},json_dumps_params={'ensure_ascii':False})

    # 添加的方法
    elif request.method=="POST":
        data=json.loads(request.body)
        name=data['name']
        category=data['category_id']
        status=data['status']
        description=data['description']
        price=data['price']
        grade=data['grade']

        result=Book.objects.create(
            name=name,
            category_id=category,
            status=status,
            description=description,
            price=price,
            grade=grade,
        )

        a=model_to_dict(result)

        return JsonResponse({"data":a},json_dumps_params={'ensure_ascii':False})

@csrf_exempt
def book_one(request,id):
    if Category.objects.filter(id=id).exists()==False:
        return JsonResponse({"msg":"不存在"})

    if request.method=="GET":
        category = Category.objects.get(id=id)
        books = category.children1.all()

        list = []
        for i in books:
            list.append({
                "id": i.id,
                "name": i.name,
                "category_id": i.category_id,
                "description": i.description,
                "created_at": i.created_at,
                "price": i.price,
                "grade": i.grade,
            })
        return JsonResponse({"data": list})
    elif request.method=="DELETE":
        category = Category.objects.get(id=id)
        category.delete()
        return JsonResponse({"msg":"删除成功"})






#修改的方法
@csrf_exempt
def update(request,id):
    book=Book.objects.get(id=id)

    if request.method=='PUT':
        data=json.loads(request.body)
        book.name=data['name']
        book.save()
        a=model_to_dict(book)
        return JsonResponse({"msg":"修改成功","id":book.name,'list':a})


# -------------------------------------------------------

# 删除的方法
@csrf_exempt
@require_http_methods(['DELETE'])
def book_two(request,id):
    book = Book.objects.get(id=id)
    book.delete()
    return JsonResponse({"msg": "删除成功"})

# 查询详情
# 删除的方法
@csrf_exempt
def selectview(request,id):
    book = Book.objects.get(id=id)

    return JsonResponse({"data":model_to_dict(book)})